// pages/borrow/borrow.js
import apiService from '../../services/api';

Page({

  data: {
    readerId: '',
    bookId: '',
    isLoading: false
  },
  onReaderIdInput(e) {
    this.setData({ readerId: e.detail.value });
  },

  onBookIdInput(e) {
    this.setData({ bookId: e.detail.value });
  },

  async onConfirmBorrow() {
    const { readerId, bookId } = this.data;
    if (!readerId || !bookId) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    this.setData({ isLoading: true });
    // 拼接SQL
    const sql = `START TRANSACTION;\n\nINSERT INTO borrow_records (reader_id, book_id, borrow_date, due_date) VALUES ('${readerId}', '${bookId}', NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY));\n\nUPDATE books SET status = '已借出' WHERE id = '${bookId}';\n\nCOMMIT;`;
    try {
      const result = await apiService.executeSql(sql);
      if (result.success) {
        wx.showToast({ title: '借书成功', icon: 'success' });
        this.setData({ readerId: '', bookId: '' });
      } else {
        wx.showToast({ title: '借书失败', icon: 'none' });
      }

    } catch (error) {
      wx.showToast({ title: '请求失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  }
})